<template>
  <div class="login-container">
    <!-- logo -->
    <div class="logo">
      <img src="@/assets/logo.png" alt="" />
    </div>

    <!-- 登录表单 -->
    <van-form @submit="onSubmit" @failed="onFailed" class="login-form" ref="loginForm">
      <van-cell-group inset>
        <!-- 用户名 -->
        <van-field
          v-model="loginFormData.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          autocomplete="username"
          clearable
          :rules="[{ required: true, message: '请填写用户名' }]"
        >
          <template #left-icon>
            <SvgIcon icon-class="login-user" size="small" />
          </template>
        </van-field>

        <!-- 密码 -->
        <van-field
          v-model="loginFormData.password"
          :type="showPassword ? 'text' : 'password'"
          name="password"
          label="密码"
          placeholder="密码"
          autocomplete="password"
          :rules="[{ required: true, message: '请填写密码' }]"
        >
          <template #left-icon>
            <SvgIcon icon-class="login-password" size="small" />
          </template>
          <template #right-icon>
            <SvgIcon
              :icon-class="showPassword ? 'login-eye-on' : 'login-eye-off'"
              size="small"
              @click.stop="showPassword = !showPassword"
            />
          </template>
        </van-field>

        <!-- 验证码 -->
        <van-field
          v-model="loginFormData.captcha"
          name="captcha"
          label="验证码"
          placeholder="请输入验证码"
          clearable
          center
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #left-icon>
            <SvgIcon icon-class="login-captcha" size="small" />
          </template>
          <template #button>
            <!-- <van-button size="small" type="primary">发送验证码</van-button> -->
            <div v-html="captchaSvg" @click="fetchCaptcha" style="cursor: pointer" />
          </template>
        </van-field>
      </van-cell-group>

      <!-- 提交按钮 -->
      <div class="footer-btns">
        <van-button round block type="default" @click="resetForm"> 重置 </van-button>
        <van-button round block type="primary" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
import type { ILoginRequest } from '@/types/apis/auth'
import { getCaptchaApi } from '@/apis/auth'

// 路由器实例
const router = useRouter()
// 路由实例
const route = useRoute()

// 验证码 SVG 内容
const captchaSvg = ref('')
/**
 * 获取验证码
 */
const fetchCaptcha = async () => {
  try {
    const { svg, text } = await getCaptchaApi()
    captchaSvg.value = svg
    console.log('验证码:', text)
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  fetchCaptcha()
})

// 登录表单
/**
 * 获取默认表单数据
 */
const getDefaultFormData = (): ILoginRequest => ({
  username: 'admin',
  password: '123456',
  captcha: 'cccc',
})
// 表单数据
const loginFormData = ref<ILoginRequest>(getDefaultFormData())
// 表单实例
const loginForm = ref()
// 是否显示密码
const showPassword = ref(false)

/**
 * 重置表单及验证
 */
const resetForm = () => {
  loginFormData.value = getDefaultFormData()
  showPassword.value = false
  loginForm.value.resetValidation()
}
/**
 * 表单提交
 * @param values 表单数据
 */
const { login } = useUserStore()
const onSubmit = async (values: ILoginRequest) => {
  console.log('submit', values)
  // 调用登录接口
  try {
    const res = await login(values)
    console.log('登录成功', res)
    // 跳转到首页
    router.replace((route.query.redirect as string) || '/home')
  } catch (error: any) {
    console.error(error)

    // error.response?.data?.message 接口返回的message
    // error.message JS抛出的错误信息
    const message = error.response?.data?.message || error.message || '登录失败'

    showFailToast(message)

    // 抛出异常给外部捕获
    // throw error
  }
}
/**
 * 表单验证失败
 */
const onFailed = (errorInfo: any) => {
  console.log('failed', errorInfo)
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100%;
  overflow: auto; // 只允许内部滚动（如果内容真的超出）
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  // logo
  .logo {
    width: 180px;
    height: 70px;
    margin-bottom: 40px;
    img {
      width: 100%;
      height: 100%;
    }
  }

  // 登录表单
  .login-form {
    // 底部按钮
    .footer-btns {
      display: flex;
      justify-content: space-between;
      margin: 16px;
    }
  }
}
</style>
